﻿using System;
using System.Collections.Generic;
using System.Text;

// 无向图 邻接矩阵
public class GraphAdjMatrix<T> : IGraph<T>
{
    private GraphNode<T>[] nodes; //顶点数组
    private int numEdges;// 边的数量
    private int[,] matrix;//邻接矩阵数组

    public GraphAdjMatrix(int n)
    {
        nodes = new GraphNode<T>[n];
        matrix = new int[n, n];
        numEdges = 0;
    }

    // 获取索引为 index 的顶点信息
    public GraphNode<T> GetNode(int index)
    {
        return nodes[index];
    }

    // 设置索引为index 的顶点信息
    public void SetNode(int index, GraphNode<T> v)
    {
        nodes[index] = v;
    }

    public int NumEdges { get { return numEdges; } set { numEdges = value; } }

    // 获取 matrix[index1,index2]的值
    public int GetMatrix(int index1, int index2)
    {
        return matrix[index1, index2];
    }

    // 设置matrix[index1,index2] 的值
    public void SetMatrix(int index1, int index2)
    {
        matrix[index1, index2] = 1;
    }

    public void DelEdge(GraphNode<T> v1, GraphNode<T> v2)
    {
        if (!IsNode(v1) || !IsNode(v2))
        {
            Console.WriteLine("Node is not belong to graph");
            return;
        }

        // 存在边，存在连接
        if (matrix[GetIndex(v1), GetIndex(v2)] == 1)
        {
            // 矩阵是对称矩阵
            matrix[GetIndex(v1), GetIndex(v2)] = 0;
            matrix[GetIndex(v2), GetIndex(v1)] = 0;
            --numEdges;
        }
    }

    public int GetNumOfEdge()
    {
        return numEdges;
    }

    public int GetNumOfVertex()
    {
        return nodes.Length;
    }

    // 判断v是否为图的顶点
    public bool IsNode(GraphNode<T> v)
    {
        foreach (GraphNode<T> node in nodes)
        {
            if (v.Equals(node))
            {
                return true;
            }
        }
        return false;
    }

    // 获取顶点v在顶点数组中的索引
    public int GetIndex(GraphNode<T> v)
    {
        int i = -1;
        for (i = 0; i < nodes.Length; i++)
        {
            if (nodes[i].Equals(v))
            {
                return i;
            }
        }
        return -1;
    }

    public bool IsEdge(GraphNode<T> v1, GraphNode<T> v2)
    {
        if (!IsNode(v1) || !IsNode(v2))
        {
            Console.WriteLine("Node is not belong to graph");
            return false;
        }

        if (matrix[GetIndex(v1), GetIndex(v2)] == 1)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public void SetEdge(GraphNode<T> v1, GraphNode<T> v2, int v)
    {
        if (!IsNode(v1) || !IsNode(v2))
        {
            Console.WriteLine("Node is not belong to graph");
            return;
        }

        // 不是无向图
        if (v != 1)
        {
            Console.WriteLine("Weight is not right");
            return;
        }

        // 矩阵是对称矩阵
        matrix[GetIndex(v1), GetIndex(v2)] = v;
        matrix[GetIndex(v2), GetIndex(v1)] = v;
        ++numEdges;
    }
}
